package com.liang.cloud.Service.impl;

import com.liang.cloud.Emun.ResultEnum;
import com.liang.cloud.Entity.Cart;
import com.liang.cloud.Entity.ProductInfo;
import com.liang.cloud.Exception.SellException;
import com.liang.cloud.Feign.ProductFeign;
import com.liang.cloud.Repository.CartRepository;
import com.liang.cloud.Service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author: 余亮亮
 * @description:
 * @create: 2020-01-29 14:27:14
 **/
@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    CartRepository cartRepository;
    @Autowired
    ProductFeign productFeign;
    @Override
    public List<Cart> findByOpenid(String openid) {
        return cartRepository.findByOpenid(openid);
    }

    @Override
    public Cart addCart(Cart cart) {
        ProductInfo productInfo = productFeign.findOne(cart.getProductId());
        if (productInfo==null){
            throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
        }
        List<Cart> cartList = cartRepository.findByOpenid(cart.getOpenid());
        for(Cart cart1 : cartList){
            if (cart1.getProductId().equals(cart.getProductId())){
                cart.setQuantity(cart.getQuantity()+cart1.getQuantity());
                cart.setCartId(cart1.getCartId());
            }
        }
        cartRepository.save(cart);
        return cart;
    }

    @Override
    public Cart sava(Cart cart) {
        return cartRepository.save(cart);
    }

    @Override
    public void delete(List<Integer> list) {
        cartRepository.deleteByCartIdIn(list);
    }

    @Override
    public void deleteByOpenid(String openid) {
        cartRepository.deleteByOpenid(openid);
    }
}
